﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using ThuVien;

namespace TranTekBE
{
    public partial class Default : BasePage
    {
        User user = new User();
        protected void Page_Load(object sender, EventArgs e)
        {
            // check Ip cho phép vào web không
            ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "LoadJS", "LoadJS();", true);
            if (Session["CheckIPAllow"] == null || Session["CheckIPAllow"].ToString() == "0")
                Session["CheckIPAllow"] = FunctionsUtils.ConvertToInt(FunctionsUtils.GetValueStringFromQueryString("ad", "0"), 0);

            //Session["IP_Wan_Client"] = hdgetip.ToString();



        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            ltLoginErr.Text = string.Empty;

            bool bResult = this.CheckDataLogin();
            string page = "Home.aspx";
            if (Session["url_click"] != null)
                page = Session["url_click"].ToString();


            if (bResult == false)
                return;
            string sql_login = null;
            string sql_User_KPI = "";
            //string FirstName = null;
            string IdUser = null;
            string UserName = null;
            string UserPass = null;
            string UserStores = null;
            string UserFName = null;
            string UserLName = null;
            bool Admin = false;
            bool AdminKPI = false;
            bool ManagerKPI = false;
            bool MemberKPI = false;

            sql_login = @"select C001900 as IdUser, C001904 as FirstName,C001905 as LastName, C001901 as UserName,
                            CONVERT(varchar(max),C001902,2) as PassName, C001909 as Stores,
                            CONVERT(varchar(max),C001903,2) as Permission
                            from T0019 
                            where C001913 > 0
                            and C001901 = '" + txtUserName.Text + @"'
                        ";
            DataSet ds_login = FunctionsUtils.Database.ExecuteQuery(sql_login);

            if (ds_login != null && ds_login.Tables.Count > 0 && ds_login.Tables[0].Rows.Count > 0)
            {
                IdUser = ds_login.Tables[0].Rows[0]["IdUser"].ToString();
                UserName = ds_login.Tables[0].Rows[0]["UserName"].ToString();
                UserPass = ds_login.Tables[0].Rows[0]["PassName"].ToString();
                UserStores = ds_login.Tables[0].Rows[0]["Stores"].ToString();
                UserFName = ds_login.Tables[0].Rows[0]["FirstName"].ToString();
                UserLName = ds_login.Tables[0].Rows[0]["LastName"].ToString();
                string PermissionUser = ds_login.Tables[0].Rows[0]["Permission"].ToString();


                if (PermissionUser == "0001000000FFFFFFFF010000000000000006010000000754484F4E472D320B")
                { Admin = true; }


                string sPassword = (txtPassword.Text.Trim().Length > 0 ? FunctionsUtils.EncryptNonDecrypt(txtPassword.Text, HashAlgorithmMode.md5) : string.Empty);

                if (UserPass == sPassword)
                {

                    Session["Login"] = true;
                    user.UserID = IdUser.ToString();
                    user.FirstName = UserFName.ToString();
                    user.LastName = UserLName.ToString();
                    user.Stores = UserStores.ToString();
                    user.UserISN = 1;
                    user.UserName = UserName.ToString();
                    this.UserInfo = user;
                    user.Admin = Admin;


                    // Insert Database 2
                    InsertDatabase2();
                    // Check Permission User KPI
                    sql_User_KPI = "SELECT ID_USER,PHAN_QUYEN FROM tbl_UserKPI Where ID_USER = '" + user.UserID + "'";
                    DataSet ds = FunctionsUtils.Database2.ExecuteQuery(sql_User_KPI);
                    string phan_quyen = ds.Tables[0].Rows[0]["PHAN_QUYEN"].ToString();
                    if (phan_quyen == "admin")
                    { AdminKPI = true; }
                    else
                        if (phan_quyen == "manager")
                        { ManagerKPI = true; }
                        else
                        { MemberKPI = true; }
                    user.AdminKPI = AdminKPI;
                    user.ManagerKPI = ManagerKPI;
                    user.MemberKPI = MemberKPI;
                    //End
                    Response.Redirect(page, true);

                }
                else
                    ltLoginErr.Text = FunctionsUtils.Msg["frm_NotLogin"];


            }


        }


        public bool CheckDataLogin()
        {
            bool bResult = true;

            if (txtUserName.Text.Trim().Length == 0)
            {
                FunctionsUtils.ShowSmallError(ltUserNameErr, FunctionsUtils.Msg["frm_Required"]);
                bResult = false;
            }

            return bResult;
        }
        public void InsertDatabase2()
        {
            try
            {
                // Insert User khi login lần đầu tiên vào DB2
                if (CheckDataExist(UserInfo.UserID) == 1)
                {
                    string sql_insert_user_login = @"
                                    INSERT INTO tbl_UserKPI
                                    (ID_USER,NAME_USER, PHAN_QUYEN, NGAY_VAO_LAM, NGAY_NGHI_VIEC, HO_USER, TEN_USER, CUA_HANG, QUAN_LY, TONG_DIEM_KPI,CHI_TIEU_DOANH_SO_THANG) values 
                                    ('" + user.UserID.ToString().Trim() + "','" + user.UserName.ToString().Trim() + "', 'user', '05-05-2012', '01-01-2200', N'" + user.LastName + "', N'" + user.FirstName + "', '" + user.Stores.ToString() + @"', 'Admin', 0,0)
                                    
                                    ";
                    FunctionsUtils.Database2.ExecuteNonQuery(sql_insert_user_login);
                }

            }
            catch (Exception err)
            {
                lbErr.Text = err.Message;
            }
        }
        public static int CheckDataExist(string checkIdUser)
        {


            string sql_so_sanh = @"SELECT ID_USER from tbl_UserKPI where ID_USER = '" + checkIdUser + "'";

            DataSet ds = FunctionsUtils.Database2.ExecuteQuery(sql_so_sanh);
            if (FunctionsUtils.isDataSetNullOrEmpty(ds) == true)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }//
    }
}
